﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using CentralOffice.PublicAffair.Data;

using PostTable = CentralOffice.PublicAffair.Data.PostDataSet.PostsDataTable;
using PostRow = CentralOffice.PublicAffair.Data.PostDataSet.PostsRow;

using PostReplyTable = CentralOffice.PublicAffair.Data.PostReplyDataSet.PostReplyDataTable;
using PostReplyRow = CentralOffice.PublicAffair.Data.PostReplyDataSet.PostReplyRow;
using Husb.Util.Enum;
using Husb.Util;
using CentralOffice.PublicAffair.BusinessActions;


namespace CentralOffice.WebClient.PublicAffairs
{
    public partial class PostEdit : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                SiteUtil.PopulateListBox(ddlPostType, SiteConstants.PostType, false);
                SetFields(HttpContext.Current.Request.QueryString["id"]);
            }
        }

        private void SetFields(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                PostRow post = CentralOffice.PublicAffair.BusinessActions.Post.GetById(new Guid(id));

                txtName.Text = post.Name;
                post.Category = Husb.Util.EnumUtil.GetInt32(SiteConstants.PostType, CategoryDataSourceType.Xml, ddlPostType.SelectedItem.Text);

                //txtNoticeNumber.Text = notice.NoticeNumber;
                //txtQueryNumber.Text = notice.QueryNumber;
                
                //txtIsTop.Text = notice.IsTop;
                //txtAccepter.Text = notice.Accepter;
                //txtPublishDate.Text = notice.PublishDate;
                //txtStatus.Text = notice.Status;

                chkAll.Checked = post.Accepter == "*";
                if (!chkAll.Checked)
                {
                    txtAccepter.Value = post.Accepter;
                    txtAccepterReadOnly.Value = post.Accepter;
                }
                txtContentText.Value = post.ContentText;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string postId = HttpContext.Current.Request.QueryString["id"];
           
            PostReplyDataSet replyDataSet;
            PostDataSet postDataSet = GetFields(postId, out replyDataSet);


            Post.Update(postDataSet, replyDataSet);

            Response.Redirect("PostView.aspx?id=" + (postDataSet.Posts.Rows[0] as PostRow).Id.ToString());
            //lblJavaScript.Text = "<script type=\"text/javascript\">window.open('DepartmentAdd.aspx');</script>";
        }

        private PostDataSet GetFields(string id, out PostReplyDataSet replyDataSet)
        {
            PostDataSet postDataSet = null;
            PostRow post = null;
            replyDataSet = new PostReplyDataSet();
            if (String.IsNullOrEmpty(id))
            {
                // new
                postDataSet = new PostDataSet();
                post = postDataSet.Posts.NewPostsRow();
                SiteUtil.PopulateCommonField(post, Guid.NewGuid());
                //post.Status = txtAccepter.Value.Length > 0 ? Husb.Util.EnumUtil.GetDisplayName(SiteConstants.TaskStatus, CategoryDataSourceType.Xml, 1) : Husb.Util.EnumUtil.GetDisplayName(SiteConstants.TaskStatus, CategoryDataSourceType.Xml, 0);
                post.Status = 1;
                
                //AddHistoryRow(historyDataSet, "添加新任务：" + txtName.Text, 1, post.Id);
                if (chkAll.Checked)
                {
                    post.Accepter = "*";
                }
                else
                {
                    post.Accepter = txtAccepter.Value.Trim(SiteConstants.CommonSeparatorChar);
                }
            }
            else
            {
                // update
                post = CentralOffice.PublicAffair.BusinessActions.Post.GetById(new Guid(id));

                //int status = Husb.Util.EnumUtil.GetInt32(SiteConstants.TaskStatus, CategoryDataSourceType.Xml, post.Status);
                if (chkAll.Checked)
                {
                    post.Accepter = "*";
                }
                else
                {
                    post.Accepter = CommonUtil.StringArray2String(CommonUtil.Merge(
                    post.Accepter.Trim(SiteConstants.CommaSeparatorChar).Split(SiteConstants.CommaSeparatorChar),
                    txtAccepter.Value.Trim(SiteConstants.CommaSeparatorChar).Split(SiteConstants.CommaSeparatorChar)
                    ), false);
                }
                
                postDataSet = post.Table.DataSet as PostDataSet;
            }

            post.Name = txtName.Text;
            post.Category = Husb.Util.EnumUtil.GetInt32(SiteConstants.PostType, CategoryDataSourceType.Xml, ddlPostType.SelectedItem.Text);

            //post.Attachments
            string fileName = SaveFile(SiteUtil.GetPostPath(), FileUpload1);
            if (fileName.Length > 0)
            {
                post.Attachments = fileName;
            }
            post.Author = CommonUtil.TrimAll(ApplicationContext.ActualUserName);
            post.ContentText = txtContentText.Value;
            post.Name = txtName.Text;

            if (String.IsNullOrEmpty(id))
            {
                AddReplyRow(out replyDataSet, true, post.Id, fileName);
            }
            else
            {
                AddReplyRow(out replyDataSet, false, post.Id, fileName);
            }

            if (String.IsNullOrEmpty(id))
            {
                postDataSet.Posts.AddPostsRow(post);
            }

            return postDataSet;
        }

        private void AddReplyRow(out PostReplyDataSet replyDataSet, bool isNew, Guid postId, string attachments)
        {
            PostReplyRow row = null;
            replyDataSet = new PostReplyDataSet();
            if (isNew)
            {
                row = replyDataSet.PostReply.NewPostReplyRow();
                row.Id = Guid.NewGuid();
                if (!String.IsNullOrEmpty( attachments) )

                {
                    row.Attachments = attachments;
                }
                
                row.PostId = postId;
                row.ReplyBy = CommonUtil.TrimAll(ApplicationContext.ActualUserName);
                row.ReplyDate = DateTime.Now;
                row.ReplyText = txtContentText.Value;
                row.ReplyTitle = txtName.Text;

                replyDataSet.PostReply.AddPostReplyRow(row);
            }
            else
            {
                row = CentralOffice.PublicAffair.BusinessActions.PostReply.GetFirstReply(new Guid(Request.QueryString["id"]));
                //row = CentralOffice.PublicAffair.BusinessActions.Post.GetById(new Guid(Request.QueryString["id"]));

                if (!String.IsNullOrEmpty(attachments))
                {
                    row.Attachments = attachments;
                }
                //row.PostId = postId;
                row.ReplyBy = CommonUtil.TrimAll(ApplicationContext.ActualUserName);
                //row.ReplyDate = DateTime.Now;
                row.ReplyText = txtContentText.Value;
                row.ReplyTitle = txtName.Text;

                replyDataSet = row.Table.DataSet as PostReplyDataSet;
            }

            
        }

        private string SaveFile(string rootDir, FileUpload file)
        {
            string fileName = "";

            string path = Server.MapPath(rootDir);
            if (file.HasFile)
            {
                //file.SaveAs(path + file.FileName);
                //fileName = rootDir + file.FileName;
                var fn = SiteUtil.GetUploadFileName(path, file.FileName);
                file.SaveAs(fn);
                fileName = rootDir + fn.Substring(fn.LastIndexOf('\\') + 1);
            }
            else
            {
                
            }
            return fileName;
        }

        protected void btnShowPopup_Click(object sender, EventArgs e)
        {
            string[] assignedBy = txtAccepter.Value.Split(',');

            tvEmp.Nodes.Clear();
            HumanResources.HumanResourcesHelper.PopulateEmployeeTree(tvEmp, true, assignedBy);

            updPnlDepartment.Update();
            mdlDetailView.Show();

        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            // 保存弹出窗口所更新的信息
            string departments = "";
            string departmentsId = "";

            if (tvEmp.CheckedNodes.Count > 0)
            {
                foreach (TreeNode node in tvEmp.CheckedNodes)
                {
                    if (!node.Text.StartsWith("["))
                    {
                        departments += node.Text + ",";
                        departmentsId += node.Value + ",";
                    }
                }
            }
            txtAccepterReadOnly.Value = departments.Trim(',');
            //txtAccepter.Value = departmentsId;
            txtAccepter.Value = departments.Trim(',');
        }

        protected void tvEmp_Load(object sender, EventArgs e)
        {
            this.tvEmp.Attributes.Add("OnClick", "OnTreeNodeChecked(event)");
        }
    }
}